//
//  EditViewController.m
//  AddressBook
//
//  Created by 解晓东 on 15/11/7.
//  Copyright (c) 2015年 sasa. All rights reserved.
//

#import "EditViewController.h"
#import "SAContactModel.h"

@interface EditViewController ()

@property (weak, nonatomic) IBOutlet UITextField *nameField;
@property (weak, nonatomic) IBOutlet UITextField *phoneField;
@property (weak, nonatomic) IBOutlet UIButton *saveBtn;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *editBtn;

- (IBAction)saveAction:(id)sender;
- (IBAction)editAction:(UIBarButtonItem *)sender;

@end

@implementation EditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 赋值
    self.nameField.text = self.contactModel.name;
    self.phoneField.text = self.contactModel.phone;
    
    // 添加观察者
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange) name:UITextFieldTextDidChangeNotification object:self.nameField];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange) name:UITextFieldTextDidChangeNotification object:self.phoneField];
}

#pragma mark - 修改按钮的状态
- (void)textChange {
    // 用户名和密码都不为空，按钮才能点击
    /*
     if (self.nameField.text.length && self.pwdField.text.length) {
     self.loginBtn.enabled = YES;
     } else {
     self.loginBtn.enabled = NO;
     }
     */
    
    self.saveBtn.enabled = (self.nameField.text.length && self.phoneField.text.length);
}

// 保存
- (IBAction)saveAction:(id)sender {
    // 1.关闭当前页面
    [self.navigationController popViewControllerAnimated:YES];
    // 2.通知代理
    if ([self.delegate respondsToSelector:@selector(editViewController:didSaveContact:)]) {
        // 更新数据模型
        self.contactModel.name = self.nameField.text;
        self.contactModel.phone = self.phoneField.text;
        [self.delegate editViewController:self didSaveContact:self.contactModel];
    }
}

#pragma mark - 编辑响应方法
- (IBAction)editAction:(UIBarButtonItem *)sender {
    if (self.nameField.enabled) {
        self.nameField.enabled = NO;
        self.phoneField.enabled = NO;
        [self.view endEditing:YES];
        self.saveBtn.hidden = YES;
        sender.title = @"编辑";
        // 还原回原来的数据
        self.nameField.text = self.contactModel.name;
        self.phoneField.text = self.contactModel.phone;
    } else {
        self.nameField.enabled = YES;
        self.phoneField.enabled = YES;
        [self.view endEditing:YES];
        self.saveBtn.hidden = NO;
        sender.title = @"取消";
    }
}
@end
